package com.yylending.las.lending.quota.credit;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.StorageUtils;
import com.yylending.las.lending.QuotaEvent;
import com.yylending.las.lending.quota.ApplyQuotaActivity;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Created by laixj on 2016/11/11.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class CreditAuthFragment extends BaseFragment implements CreditPresenter.View {
	private final static String TAG = "CreditAuthFragment";

	private final static int LOADER_ID = 1;
	private final static int REQUEST_CODE_BANK = 111;
	private final static int REQUEST_CODE_COMMIT = 112;
	private final static int REQUEST_CODE_AUTH_FAILURE = 113;
	private static final int PERMISSION_REQUEST_CODE = 1;

	@BindView(R.id.apply_quota_step_four)
	ImageView mApplyQuotaStepFour;
	@BindView(R.id.apply_quota_step_four_rl)
	RelativeLayout mApplyQuotaStepFourRl;
	@BindView(R.id.authority_confirm_btn)
	Button mNext;
	Unbinder unbinder;
	@BindView(R.id.auth_hint1)
	TextView mAuthHint1;
	@BindView(R.id.credit_authorization_iv)
	ImageView mCreditAuthorizationIv;
	@BindView(R.id.authority_hint2)
	TextView mAuthorityHint2;

	private CreditPresenter mPresenter;
	private CreditModel.VerifyInfo mVerifyInfo;
	private String mAuthCode = "";

	public static BaseFragment newInstance(int sectionNumber) {
		BaseFragment fragment = new CreditAuthFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(getActivity(), new CreditPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (CreditPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getLoaderManager().initLoader(LOADER_ID, null, this);
		PermissionsGrantedHelper.PermissionsAllGranted(mRxPermissions, mGrantedListener, PERMISSION_REQUEST_CODE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
	}

	@Override
	public void onDetach() {
		super.onDetach();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_credit_auth, null);
		unbinder = ButterKnife.bind(this, v);
		mAuthorityHint2.setText(getString(R.string.verify_bank_card_hint2, getString(R.string.app_name)));
		return v;
	}

	@Override
	public void getVerifyInfoSuccess(CreditModel.VerifyInfo verifyInfo) {
		mVerifyInfo = verifyInfo;
		AuthWebViewActivity.startForResult(this, verifyInfo, REQUEST_CODE_BANK);
	}

	@Override
	public void creditHasLimited() {
		((ApplyQuotaActivity) getActivity()).showFragment(ApplyQuotaActivity.PAGE_ID_CREDIT_AUTH_LIMITED, null);
	}

	@Override
	public void getVerifyInfoFail(String msg) {
		showToast(msg);
	}

	@Override
	public void saveVerifyCodeSuccess() {

	}

	@Override
	public void saveVerifyCodeFail(String msg) {

	}

	@Override
	public void saveVerifyCodeRetCode(String retCode) {

	}

	@Override
	public void onDestroyView() {
		getLoaderManager().destroyLoader(LOADER_ID);
		super.onDestroyView();
		unbinder.unbind();
	}

	@OnClick({R.id.authority_confirm_btn})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.authority_confirm_btn:
				//获取征信授权码成功
				//clearAuthCode();
				//AuthCommitActivity.startForResult(this, REQUEST_CODE_COMMIT, mAuthCode);
				if (mNext.getText().equals(getString(R.string.verify_bank_card))) {
					clearAuthCode();
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_START_AD);
					mPresenter.getVerifyInfo(Constants.AUTH_SOURCE_TYPE_PC, Constants.AUTH_MERCHANT_ADDRESS);
				} else if (mNext.getText().equals(getString(R.string.complete))) {
					StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CREDIT_AUTHORIZATION_PASSED);
					EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
					getActivity().finish();
				}
				break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		CLog.i(TAG, "onActivityResult=" + requestCode);
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case REQUEST_CODE_BANK:
				if (resultCode == RESULT_OK) {
					//mAuthCode = "";
					mAuthCode = data.getStringExtra(Constants.BANK_AUTH_CODE);
					//获取征信授权码成功
					AuthCommitActivity.startForResult(this, REQUEST_CODE_COMMIT, mAuthCode);
				}
				break;
			case REQUEST_CODE_COMMIT:
				if (resultCode == RESULT_OK) {
					if (data.getBooleanExtra(Constants.BANK_AUTH_PASSED, false)) {
						//授权成功
						authSuccess();
					} else {
						//授权失败
						AuthFailureActivity.startForResult(this, REQUEST_CODE_AUTH_FAILURE);
					}
				}else{
					if(resultCode == RESULT_CANCELED && null != data && data.getBooleanExtra(Constants.BANK_AUTH_LIMITED, false)){
						creditHasLimited();
					}
					clearAuthCode();
				}
				break;
			case REQUEST_CODE_AUTH_FAILURE:
				if (resultCode == RESULT_OK) {
					clearAuthCode();
				}
				break;
			default:
				break;
		}
	}

	private void authSuccess() {
		clearAuthCode();
		//mCreditAuthorizationIv.setImageResource(R.drawable.ic_authority_passed);
		//mAuthHint1.setText(R.string.credit_authority_success);
		//mNext.setText(R.string.complete);
		showToast(R.string.submit_success);
		EventAgent.post(new QuotaEvent.RefreshStatusEvent(QuotaEvent.Event.QUOTA_REFRESH, null));
		getActivity().finish();
	}

	private void clearAuthCode() {
		mAuthCode = "";
		String filePath = String.format(StorageUtils.SCREENSHOT_FILE_PATH_TEMPLATE, Environment.getExternalStorageDirectory().toString(), StorageUtils.SCREENSHOTS_DIR_NAME, StorageUtils.SCREENSHOT_FILE_NAME_TEMPLATE);
		StorageUtils.deleteFile(filePath);
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.WRITE_EXTERNAL_STORAGE:
					if (permission.granted) {

					} else {

					}
					break;
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {
			switch (requestCode) {
				case PERMISSION_REQUEST_CODE:
					if (granted) {

					} else {

					}
					break;
				default:
					break;
			}
		}
	};
}